package com.eatrip.dao.implementation;


import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.eatrip.bean.User;
import com.eatrip.dao.UserDAO;

@Repository
@Transactional
public class UserDAOImple implements UserDAO {

	private HibernateTemplate hibernateTemplate;


	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Autowired
	private SessionFactory sessionFactory;

	//si usa quando si hanno le liste
	@SuppressWarnings("unchecked")
	@Override
	public User getUser(String username, String password){
		User user = new User();
		//in pratica sono le condizioni nella clausula where
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("email", username))
				.add(Restrictions.eq("password", password));
		
		List<User> list = criteria.list();

		if (list.size() == 0)
			return null;

		user = list.get(0);

		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public User getUserByEmail(String email){
		User user = new User();
		//in pratica sono le condizioni nella clausula where
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("email", email));

		List<User> list = criteria.list();

		if (list.size() == 0)
			return null;

		user = list.get(0);

		return user;
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAllUser(){
		return hibernateTemplate.find("from Autenticazione");
	}

	@Override
	public void insertUser(User user){
		hibernateTemplate.saveOrUpdate(user);
	}
	
	@Override
	public void deleteUser(User user){
		hibernateTemplate.delete(user);
	}
	
	@Override
	public void deleteAllUser(){
		Query q = sessionFactory.getCurrentSession().createQuery("DELETE FROM Autenticazione");
		int row  = q.executeUpdate();
		if (row==0)
			System.out.println("errore nella cancellazione deleteAllUser");
	}



}
